//
// ========================================================================
// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//

package org.eclipse.jetty.ee11.websocket.tests;

import java.io.IOException;
import java.net.URI;
import java.util.EnumSet;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import jakarta.servlet.DispatcherType;
import org.eclipse.jetty.ee11.servlet.ServletContextHandler;
import org.eclipse.jetty.ee11.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.ee11.websocket.servlet.WebSocketUpgradeFilter;
import org.eclipse.jetty.http.pathmap.PathSpec;
import org.eclipse.jetty.http.pathmap.UriTemplatePathSpec;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.websocket.api.Callback;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class JettyWebSocketServletAttributeTest
{
    private Server server;
    private ServerConnector connector;
    private WebSocketClient client;
    private final EchoSocket serverEndpoint = new EchoSocket();

    @BeforeEach
    public void before()
    {
        server = new Server();
        connector = new ServerConnector(server);
        server.addConnector(connector);

        client = new WebSocketClient();
    }

    @AfterEach
    public void stop() throws Exception
    {
        client.stop();
        server.stop();
    }

    public void start(JettyWebSocketServletContainerInitializer.Configurator configurator) throws Exception
    {
        ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        contextHandler.setContextPath("/");
        server.setHandler(contextHandler);
        JettyWebSocketServletContainerInitializer.configure(contextHandler, configurator);

        server.start();
        client.start();
    }

    @Test
    public void testAttributeSetInNegotiation() throws Exception
    {
        String customHeaderName = "myWebSocketCustomAttribute";
        String customHeaderValue = "foobar";
        start((context, container) ->
        {
            // Add a custom filter that sets an attribute on the request.
            context.addFilter("CustomFilter", (request, response, chain) ->
            {
                request.setAttribute(customHeaderName, customHeaderValue);
                chain.doFilter(request, response);
            }).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");

            // Add the WebSocketUpgradeFilter manually so it is after the custom filter.
            context.addFilter(WebSocketUpgradeFilter.class.getName(), WebSocketUpgradeFilter.class)
                .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

            container.addMapping("/", (req, resp) ->
            {
                // The UpgradeRequest should have the custom attribute set by the filter.
                assertThat(req.getServletAttribute(customHeaderName), equalTo(customHeaderValue));
                return serverEndpoint;
            });
        });

        URI uri = URI.create("ws://localhost:" + connector.getLocalPort() + "/filterPath");
        EventSocket clientEndpoint = new EventSocket();
        client.connect(clientEndpoint, uri);
        assertTrue(clientEndpoint.openLatch.await(5, TimeUnit.SECONDS));

        // Assert we have a normal close, meaning the servlet attribute was set correctly.
        clientEndpoint.session.close();
        assertTrue(clientEndpoint.closeLatch.await(5, TimeUnit.SECONDS));
        assertThat(clientEndpoint.closeCode, is(StatusCode.NORMAL));
    }

    @Test
    public void testPathSpecAttribute() throws Exception
    {
        start((context, container) -> container.addMapping("uri-template|/{path}", (req, resp) ->
        {
            UriTemplatePathSpec pathSpec = (UriTemplatePathSpec)req.getServletAttribute(PathSpec.class.getName());
            assertNotNull(pathSpec);

            Map<String, String> params = pathSpec.getPathParams(req.getRequestPath());
            String path = params.get("path");
            assertNotNull(path);

            return new ParamWebSocketEndPoint(path);
        }));

        String param = "world";
        URI uri = URI.create("ws://localhost:" + connector.getLocalPort() + "/" + param);
        EventSocket clientEndpoint = new EventSocket();
        try (Session session = client.connect(clientEndpoint, uri).get(5, TimeUnit.SECONDS))
        {
            session.sendText("hello", Callback.NOOP);
            String path = clientEndpoint.textMessages.poll(5, TimeUnit.SECONDS);
            assertEquals(param, path);
        }
    }

    @WebSocket
    public static class ParamWebSocketEndPoint
    {
        private final String param;

        public ParamWebSocketEndPoint(String param)
        {
            this.param = param;
        }

        @OnWebSocketMessage
        public void onText(Session session, String text) throws IOException
        {
            session.sendText(param, Callback.NOOP);
        }
    }
}
